package com.qf.commons;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinyinUtil {

    /**
     * 将文本内容转换成拼音
     * @param text
     * @return
     */
    public static String toPinyin(String text){

        HanyuPinyinOutputFormat hanyuPinyinOutputFormat = new HanyuPinyinOutputFormat();
        hanyuPinyinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        StringBuilder stringBuilder = new StringBuilder();

        char[] chars = text.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];

            try {
                String[] strings = PinyinHelper.toHanyuPinyinStringArray(c, hanyuPinyinOutputFormat);
                if (strings != null) {
                    stringBuilder.append(strings[0]);
                } else {
                    stringBuilder.append(c);
                }
            } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                badHanyuPinyinOutputFormatCombination.printStackTrace();
            }
        }

        return stringBuilder.toString();
    }
}
